<?php


class ObservationTable extends Doctrine_Table
{
    
    public static function getInstance()
    {
        return Doctrine_Core::getTable('Observation');
    }

    /**
     *
     * @param <type> $array
     * @param <type> $researchId
     * @return <type> 
     */
    public function bulkInsertUpdate($array) {

        if ($array == null) {
            return false;
        }

        $records = new Doctrine_Collection($this->getTableName());

        foreach($array as $item) {

            if (is_null($item) || $item == "")
                continue;

            $record;

            if (isset($item['id'])) {
                $record = $this->find(array($item['id']));
            } else {
                $record = new Observation($this->getTableName(), true);
                $record->setResearchid($item['researchid']);
                $record->setCreatebyuserid($item['createbyuserid']);
            }

            $record->setLocation($item['location'])
                    ->setLat($item['lat'])
                    ->setLng($item['lng'])
                    ->setRemarks($item['remarks'])
                    ->setObservationdate($item['observationdate'])
                    ->setApprovalstatustyperefid(Types::$RESEARCH_APPROVAL_STATUS[Types::$APPR_NEW])
                    ->setModifiedbyuserid($item['modifiedbyuserid']);

            $records->add($record);
        }

        try {
            $records->save();
            return true;
        } catch (Exception $e) {
            sfContext::getInstance()->getLogger()->debug($e->getMessage());
            sfContext::getInstance()->getLogger()->debug($e->getTraceAsString());
            return false;
        }

        return true;
    }

    /**
     * Insert a collection of mapped key values array
     * @param array $array      array of mapped key values array
     * @return boolean
     */
    public function insertCollection($array) {

        if ($array == null) {
            return false;
        }

        $records = new Doctrine_Collection($this->getTableName());

        foreach($array as $item) {
            if (empty($item))
                continue;

            $record = $this->create($item);
            $records->add($record);
        }

        try {
            $records->save();
            return true;

        } catch (Exception $e) {
            if (sfConfig::get('sf_logging_enabled'))
            {
              sfContext::getInstance()->getLogger()->debug($e->getMessage());
            }
            throw $e;
        }

    }

    /**
     * Update bulk
     * @param array $array array of mapped key values array
     * @return boolean
     */
    public function updateCollection($array) {
        if ($array == null) {
            return false;
        }

        // get all id
        foreach ($array as $item) {
            $ids[] = $item['id'];
        }

        // get all records
        $records;
        $where = 'id in (?'. str_repeat(',?', count($ids)-1) .')';
        try {
            $records = $this->findByDql($where, $ids);
        } catch (Exception $e) {
            sfContext::getInstance()->getLogger()->debug('find: '. $e->getMessage());
        }
        

        // build mapped id => record        
        foreach ($records as $rec) {
            $indexed[$rec->id] = $rec;
        }

        // iterate to update values
        foreach ($array as $item) {
            if (empty($item))
                continue;

            $record = $indexed[$item['id']];

            foreach ($item as $key => $value) {
                $record->set($key, $value);
            }
        }

        try {
            $records->save();
            return true;

        } catch (Exception $e) {
            if (sfConfig::get('sf_logging_enabled'))
            {
              sfContext::getInstance()->getLogger()->debug($e->getMessage());
            }
            throw $e;
        }
    }

    /**
     *
     * @param array $keys array of id
     * @return boolean
     */
    public function delete($keys){
        try {
            $to_remove_records = $this->findByDql('id IN (?' . str_repeat(',?', count($keys)-1) . ')', $keys);
            $to_remove_records->delete();
            return true;
        } catch (Exception $e) {
            if (sfConfig::get('sf_logging_enabled'))
            {
              sfContext::getInstance()->getLogger()->debug($e->getMessage());
            }
            return false;
        }
    }
}